<?php

namespace App\Controller\App;

use App\Base\BaseController4Restful;
use App\Entity\User;
use App\Event\UserEvent;
use App\Repository\UserRepository;
use App\Service\Wechat\WechatLogin;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class MiniAppUserController extends BaseController4Restful
{
    /**
     * @Route("/api/user/reg/wx_mini_app", name="apiUserRegWxMiniApp",methods={"GET","POST"})
     */
    public function apiGetUsers(
        UserRepository $repository,
        Request $request,
        WechatLogin $wechat,
        EventDispatcherInterface $dispatcher
    )
    {
        if(!$code = $this->getParamRequired("code")){return $this->json_out(400,"缺少code参数");}
        $wechat->getOpenidAndAccessToken($code);
        $openid = $wechat->Openid;
        if ($openid) {
            $req = $this->getRequestData();
            $name = $req["name"]??'用户'.rand(10000,99999);
            $pic = $req["pic"]??'';
            //获取到了就开始注册流程
            $user = $repository->findOneBy(array("openid"=>$openid));
            if ($user) {
                //已经存在用户直接完成注册
                //--修改一下头像昵称
                $user->setName($name)
                    ->setPic($pic);
            }else{
                $user = new User();
                $user->setPic($pic)
                    ->setName($name)
                    ->setPhone('')
                    ->setOpenid($openid)
                    ->setCreateAt(new \DateTime())
                    ->setApiToken(time())//TODO 正式环境应该是随机数字或者加密字符串
                    ->setIsOn(true);
                //检测是否有有效的推荐人信息
                $parent = $req["parent"]??"";
                $parent = $repository->find($parent);
                if ($parent) {
                    $user->setParent($parent);
                }
                //触发用户注册事件
                $event = new UserEvent($user);
                $dispatcher->dispatch($event,UserEvent::USER_REG);
            }

            $this->myEm()->persist($user);
            $this->myEm()->flush();
            return $this->json_out(200,"获取成功",$user);
        }else{
            return $this->json_out(400,"无效的code");
        }
    }
}
